package com.huobao.yunying.update;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xutils.common.util.LogUtil;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.widget.RemoteViews;

import com.huobao.zhangying.R;

/**
 * @use 下载Apk文件，并在Notifition中显示进度，下载完成后自动安装
 * @author 辛汝州
 * @date 2014-4-9
 */
public class UpdateDownloadUtil {

	private final String TAG = "DownloadUtil";
	//下载完了吗
	public static boolean downloadFinish = false;
	public static File apkPathFile = null;

	private NotificationManager mNotificationManager;
	private Notification mNotification;
	private RemoteViews mRemoteViews;
	private int max;
	private Context c;
	private Intent intent;
	private PendingIntent pi;
	private long oldProgress;
	private final String updateFolder = BaseConfig.BASE_UPDATE_APK_FOLDER;
	private File apk_path;

	
	private static UpdateDownloadUtil mDownloadUtil;
	public static UpdateDownloadUtil getInstant(){
		if(mDownloadUtil == null)
			mDownloadUtil = new UpdateDownloadUtil();
		return mDownloadUtil;
	}
	
	public void downloadAPK(Context c, String url) {
		if (url == null)
			// 不下载更新
			return;
		this.c = c;
		LogUtil.e("start download");
		new DownloadTask().execute(url);
	}

	private class DownloadTask extends AsyncTask<String, Integer, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			downloadFinish = false;
			int icon = 0;
			File file = new File(updateFolder);
			if (!file.exists())
				file.mkdirs();
			try {
				apk_path = new File(file.getAbsolutePath() + File.separator
						+ "update.apk");
				apk_path.createNewFile();
			} catch (IOException e1) {
				LogUtil.e("createNewFile fail" + e1.toString());
			}
			try {
				ApplicationInfo mPackageInfo = c.getPackageManager()
						.getApplicationInfo(c.getPackageName(),
								PackageManager.GET_META_DATA);
				icon = mPackageInfo.icon;
			} catch (NameNotFoundException e) {
			}
			mNotificationManager = (NotificationManager) c
					.getSystemService(Context.NOTIFICATION_SERVICE);
			mNotification = new Notification(icon, "下载更新包...",
					System.currentTimeMillis());
			// 将此通知放到通知栏的"Ongoing"即"正在运行"组中
			mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
			mNotification.icon = c.getApplicationInfo().icon;
			mRemoteViews = new RemoteViews(c.getPackageName(),
					R.layout.notifition_view);
			intent = new Intent("com.android.CLICK_NOTIFITION");
			pi = PendingIntent.getBroadcast(c, 0, intent, 0);
			mNotification.contentIntent = pi;
			mNotification.contentView = mRemoteViews;
			mNotificationManager.notify(0, mNotification);
		}

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			try {
				URL url = new URL(params[0]);
				HttpURLConnection httpUrl = (HttpURLConnection) url
						.openConnection();
				max = httpUrl.getContentLength() / 100;// 获取网络文件的大小
				InputStream is = url.openStream();
				FileOutputStream fos = new FileOutputStream(apk_path);
				byte[] buffer = new byte[1024];
				int len;
				int progress = 0;
				while ((len = is.read(buffer)) != -1) {
					progress += len;
					publishProgress(progress);
					fos.write(buffer, 0, len);
				}
				is.close();
				fos.close();
			} catch (Exception e) {
				LogUtil.e("error:" + e.toString());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (apk_path.exists())
				installAPK(apk_path);
			downloadFinish = true;
			apkPathFile = apk_path;
			mRemoteViews.setTextViewText(R.id.NotifitionProgressTextView,
					"下载完成，点击安装");
			mNotificationManager.notify(0, mNotification);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			long p = values[0];
			long progress = p / max;
			if (oldProgress == 0)
				oldProgress = progress;
			if (progress == oldProgress)
				return;
			else
				oldProgress = progress;
			mRemoteViews.setProgressBar(R.id.NotifitionProgressBar, 100,
					(int) progress, false);
			mRemoteViews.setTextViewText(R.id.NotifitionProgressTextView,
					"下载更新包        "+progress + "%");
			mNotificationManager.notify(0, mNotification);
		}

	}

	private void installAPK(File path) {
		Intent install = new Intent();
		install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		install.setAction(Intent.ACTION_VIEW);
		install.setDataAndType(Uri.fromFile(path),
				"application/vnd.android.package-archive");
		c.startActivity(install);// 安装
	}
}
